import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'

import toNative from '@/utils/toNative'

import Dialog from '@/components/dialog/Index'

import type { ComponentPublicInstance } from 'vue'
import { getNeedSyncInvoiceList, getNeedUploadList, syncInvoice } from '@/api/invoice'
import {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import type { BatchInvoiceDto, InvoiceDto, SyncInvoiceReqDto } from '@/api/invoice/types'
import PreviewImageOrPdf from '@/components/preview-media/PreviewImageOrPdf'
import { InvoiceTypeCnEnum } from '@/const/enum'
import { Button, Checkbox, Col, message, Row } from 'ant-design-vue'

interface InvoiceExtendDto extends InvoiceDto {
    isChecked: boolean
    disabled: boolean
    disableId: number
}

interface SelectedType extends InvoiceExtendDto {
    batchInvoice: BatchInvoiceDto
}

@Component
export class DialogRecharge extends Render {
    @Prop({ default: false }) show!: boolean

    @Prop() invoicelist!: BatchInvoiceDto[]

    @Prop() showDate!: boolean

    showDialog = false

    active = 0

    batchInvoiceList: BatchInvoiceDto[] = []
    needUploadList: InvoiceExtendDto[] = []
    selectedList: SelectedType[] = []

    @Emit('update:show')
    emitShow(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('invoicelist')
    async handleWatchBatchInvoicelist(val: BatchInvoiceDto[]) {
        if (!this.invoicelist.length) {
            this.clear()
        } else {
            this.batchInvoiceList = this.invoicelist
            this.needUploadList = await this.getUploadList(this.batchInvoiceList[0])
        }
    }

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.showDialog = this.show
        if (this.show) {
            this.basicForm = renderForm(this.basicFormConfig)
            // this.batchInvoiceList = await this.getInvoiceList()
            // if (this.batchInvoiceList.length) {
            //     this.needUploadList = await this.getUploadList(this.batchInvoiceList[0])
            // } else {
            //     this.needUploadList = []
            // }
        } else {
            // this.batchInvoiceList = []
            this.needUploadList = []
            this.selectedList = []
        }
    }

    @Watch('showDialog', { immediate: true })
    handleWatchDialogShow() {
        this.emitShow(this.showDialog)
    }

    basicFormConfig = this.initBasicFormConfig() as FormModalDto
    initBasicFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            noPadding: true,
            items: {
                month: {
                    name: '',
                    element: 'datetime',
                    type: 'month',
                    span: 6,
                    callback: {
                        change: async () => {
                            this.batchInvoiceList = await this.getInvoiceList()
                        }
                    }
                }
            },
            complete: async () => {},
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {
                initModelValue(this.basicFormConfig)
            }
        } as FormModalDto
    }

    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    get totalMoney() {
        const curList = this.selectedList.filter(i=> {
            return i.batchInvoice.id === this.batchInvoiceList[this.active].id
        })
        console.log(1234, curList)
        return curList.reduce((a, b) => a + b.amount, 0) || 0
    }

    clear() {
        this.needUploadList = []
        this.selectedList = []
    }

    async getInvoiceList() {
        const params = getModelValue(this.basicFormConfig)
        const res = await getNeedSyncInvoiceList({
            isSync: 0,
            month: params.month
        })
        return res
    }

    async getUploadList(params: BatchInvoiceDto | InvoiceExtendDto) {
        const res = (await getNeedUploadList({
            companyName: params.companyName,
            voiceType: params.type
        })) as InvoiceExtendDto[]
        res.forEach((i) => {
            i.isChecked = false
            i.disabled = false
            i.disableId = params.id
        })
        this.selectedList.forEach((i) => {
            const index = res.findIndex((j) => j.id === i.id)
            if (index !== -1) {
                const curSelect = res[index]
                if (
                    i.companyName === curSelect.companyName &&
                    i.type === curSelect.type &&
                    i.disableId !== curSelect.disableId
                ) {
                    curSelect.disabled = true
                } else {
                    curSelect.isChecked = true
                }
            }
        })
        return res
    }

    async onChange(item: BatchInvoiceDto, index: number) {
        this.active = index
        console.log(1111, index, item)
        this.needUploadList = await this.getUploadList(item)
    }

    onSelect(val: any, item: InvoiceExtendDto) {
        const index = this.selectedList.findIndex((i) => i.id === item.id)
        item.isChecked = val as boolean
        if (val && index === -1) {
            const mixedData = item as SelectedType
            mixedData.batchInvoice = this.batchInvoiceList[this.active]
            this.selectedList.push(mixedData)
        }
        if (!val && index !== -1) {
            this.selectedList.splice(index, 1)
        }
    }

    onCancel() {
        this.showDialog = false
    }

    async onConfirm() {
        if(!this.selectedList?.length) {
            message.warning('请先选择发票')
            return
        }

        const params = [] as SyncInvoiceReqDto[]
        this.selectedList.forEach(i => {
            const index = params.findIndex(k => k.uploadId === i.batchInvoice.id)
            if (index !== -1) {
                params[index].invoiceList.push({
                    id: i.id,
                    month: i.month,
                    status: i.status,
                })
            } else {
                const data = {
                    uploadId: i.batchInvoice.id,
                    invoiceUrl: i.batchInvoice.invoiceUrl,
                    invoiceList: [{
                        id: i.id,
                        month: i.month,
                        status: i.status
                    }]
                }
                params.push(data)
            }
        })

        await syncInvoice(params)
        this.showDialog = false
        this.handleRefresh()
    }

    render(data: ComponentPublicInstance) {
        return (
            <Dialog
                v-model:show={this.showDialog}
                title="冲突发票处理"
                width={1100}
                v-slots={{
                    default: () => {
                        return (
                            <>
                                <div>{this.showDate && this.basicForm.element()}</div>
                                <Row class="text-base" gutter={20}>
                                    <Col md={14} sm={24}>
                                        <div class="p-10px border-1 rounded-lg">
                                            <Row>
                                                <Col
                                                    md={14}
                                                    sm={24}
                                                    class="max-h-500px overflow-auto"
                                                >
                                                    {this.batchInvoiceList?.length ? this.batchInvoiceList.map((i, index) => {
                                                        return (
                                                            <div
                                                                class={`p-10px border-l-5 border-l-solid border-l-white cursor-pointer ${this.active === index ? 'bg-blue-100 text-blue-default !bg-opacity-20 !border-l-blue-default' : ''}`}
                                                                onClick={() =>
                                                                    this.onChange(i, index)
                                                                }
                                                            >
                                                                <Row>
                                                                    <Col lg={12} md={24}>
                                                                        产品类型：
                                                                        {InvoiceTypeCnEnum[i.type]}
                                                                    </Col>
                                                                    <Col lg={12} md={24}>
                                                                        发票月份：{i.month}
                                                                    </Col>
                                                                    <Col lg={18} md={24}>
                                                                        <div
                                                                            class="truncate"
                                                                            title={i.companyName}
                                                                        >
                                                                            {i.companyName}
                                                                        </div>
                                                                    </Col>
                                                                    <Col lg={6} md={24}>
                                                                        <PreviewImageOrPdf
                                                                            src={i.invoiceUrl}
                                                                            text="预览"
                                                                        />
                                                                    </Col>
                                                                </Row>
                                                            </div>
                                                        )
                                                    }): <div class="text-center">暂无数据</div>}
                                                </Col>
                                                <Col
                                                    md={10}
                                                    sm={24}
                                                    class="max-h-500px overflow-auto"
                                                >
                                                    {this.needUploadList.map((i, index) => {
                                                        return (
                                                            <div class="flex items-center ml-20px">
                                                                <Checkbox
                                                                    v-model:checked={i.isChecked}
                                                                    disabled={i.disabled}
                                                                    onChange={(event) =>
                                                                        this.onSelect(event, i)
                                                                    }
                                                                >
                                                                    <div class="mr-16px">
                                                                        {i.invoiceName}（{i.amount}
                                                                        元）
                                                                    </div>
                                                                </Checkbox>
                                                            </div>
                                                        )
                                                    })}
                                                    <div class="flex justify-end">
                                                        合计：{this.totalMoney}元
                                                    </div>
                                                </Col>
                                            </Row>
                                        </div>
                                    </Col>
                                    <Col md={10} sm={24} class="h-500px overflow-auto">
                                        <div class="p-10px border-1 rounded-lg">
                                            <div>已选择：</div>
                                            {this.selectedList.map((i, index) => {
                                                return (
                                                    <div class="border-b-1 py-10px border-b-solid">
                                                        <Row>
                                                            <Col lg={8} md={24}>
                                                                产品类型：
                                                                {InvoiceTypeCnEnum[i.type]}
                                                            </Col>
                                                            <Col lg={8} md={24}>
                                                                发票月份：{i.month}
                                                            </Col>
                                                            <Col lg={8} md={24}>
                                                                应用月份：{i.batchInvoice.month}
                                                            </Col>
                                                            <Col lg={18} md={24}>
                                                                <div
                                                                    class="truncate"
                                                                    title={i.companyName}
                                                                >
                                                                    {i.companyName}
                                                                </div>
                                                            </Col>
                                                            <Col lg={6} md={24}>
                                                                <PreviewImageOrPdf
                                                                    src={i.invoiceUrl}
                                                                    text="预览"
                                                                />
                                                            </Col>
                                                        </Row>
                                                    </div>
                                                )
                                            })}
                                        </div>
                                    </Col>
                                </Row>
                            </>
                        )
                    },
                    footer: () => {
                        return (
                            <div class="flex justify-center">
                                <Button type="primary" onClick={this.onConfirm}>
                                    确定
                                </Button>
                            </div>
                        )
                    }
                }}
            ></Dialog>
        )
    }
}

export default toNative<
    { invoicelist: (InvoiceDto | BatchInvoiceDto)[], showDate: boolean },
    { confirm: () => void }
        >(DialogRecharge)
